package com.na.game.engine.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.graphics.Rect;

import com.na.game.engine.GameManager;
import com.na.game.engine.GameManager.Clazz;
import com.na.game.engine.graphics.Image;
import com.na.game.engine.resource.ResourceManager;
import com.na.game.engine.util.PList.PListItem;

public class PListManager implements Clazz {

	private Map<String, PList> list = new HashMap<String, PList>();
	
	public void loadPList(String fileName) {
		if (!list.containsKey(fileName)) {
			try {
				InputStream plist = GameManager.get(ResourceManager.class).getAssets(fileName);
				BufferedReader br = new BufferedReader(new InputStreamReader(plist, "UTF-8"));
				String line = null;
				List<String> content = new ArrayList<String>();
				while ((line = br.readLine()) != null) {
					if (!line.startsWith("//")) {
						content.add(line);
					}
				}
				br.close();
				int type = Integer.parseInt(content.get(0));
				if (type == 0) { // 规则格式
					String png = content.get(1);
					Image image = GameManager.get(ResourceManager.class).getImageFromAssets(png);
					int[] loc = Util.parseInts(Util.splitStr(content.get(2), ","));
					int cols = image.getWidth() / loc[2];
					int rows = image.getHeight() / loc[3];
					PList pl = new PList(cols * rows, image);
					list.put(fileName, pl);
					int x = loc[0], y = loc[1];
					for (int i = 0; i < rows; i++) {
						for (int j = 0; j < cols; j++) {
							PListItem item = new PListItem(pl.size(), new Rect(x, y, x + loc[2], y + loc[3]));
							pl.addItem(item);
							x += loc[2];
						}
						x = loc[0];
						y += loc[3];
					}
				} else { // 不规则格式
					// TODO
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public PList getPList(String fileName) {
		return list.get(fileName);
	}
	
	@Override
	public Class<?> getClazz() {
		return getClass();
	}
}
